<script lang="ts">
  export default {
    name: 'PoleUpload',
    inheritAttrs: false,
  };
</script>
<script setup lang="ts">
  import { ref, computed } from 'vue';
  import {
    Upload,
    // Progress,
  } from '@arco-design/web-vue';
  import type { RequestOption, UploadRequest, FileItem } from '@arco-design/web-vue';
  // import { IconEdit, IconPlus } from '@arco-design/web-vue/es/icon';
  import { uploadImage } from '/@/api/common';
  // import { uuid } from '/@/utils/uuid';
  import { useUserStore } from '/@/store/modules/user';

  type ListType = 'text' | 'picture' | 'picture-card';
  interface UploadProps {
    fileList?: FileItem[];
    limit?: number;
    autoUpload?: boolean;
    showUploadList?: boolean;
    class?: any;
    listType?: ListType;
    showUploadButton?:
      | boolean
      | {
          showOnExceedLimit: boolean;
        };
    accept?: string;
  }
  const props = withDefaults(defineProps<UploadProps>(), {
    fileList: () => [],
    limit: 1,
    autoUpload: true,
    showUploadList: true,
    listType: 'picture-card',
    showUploadButton: true,
    accept: 'image/*',
  });
  const emit = defineEmits(['update:file-list', 'change']);

  const uploadRef = ref();
  const buttonRef = ref<HTMLElement>();
  const userStore = useUserStore();
  const getPrefixPath = computed(() => {
    return userStore.userInfo ? `user/${userStore.userInfo.id}` : 'app';
  });

  // 自定义上传
  const customRequest = (option: RequestOption): UploadRequest => {
    const { onProgress, onError, onSuccess, fileItem } = option;
    const controller = new AbortController();

    const upload = async () => {
      if (fileItem.file) {
        try {
          const result = await uploadImage(
            { file: fileItem.file, prefixPath: getPrefixPath.value },
            (event) => {
              const percent =
                event.total && event.total > 0 ? event.loaded / event.total : undefined;
              if (percent) {
                onProgress(percent, event as unknown as ProgressEvent<EventTarget>);
              }
            },
            controller.signal,
          );
          onSuccess(result);
        } catch (error) {
          onError(error);
        }
      }
    };
    upload();
    return {
      abort() {
        controller.abort();
      },
    };
  };

  const onChange = (fileList: FileItem[], fileItem: FileItem) => {
    emit('change', fileList, fileItem);
  };

  const onUpdateFileList = (fileList: FileItem[]) => {
    emit('update:file-list', fileList);
  };

  const submit = () => {
    uploadRef.value?.submit();
  };

  const triggerInputClick = () => {
    buttonRef.value?.click();
  };

  defineExpose({ submit, triggerInputClick });
</script>

<template>
  <Upload
    ref="uploadRef"
    response-url-key="url"
    :list-type="props.listType"
    :class="props.class"
    :file-list="props.fileList"
    :custom-request="customRequest"
    :auto-upload="props.autoUpload"
    :limit="props.limit"
    :show-file-list="props.showUploadList"
    :show-upload-button="props.showUploadButton"
    :accept="props.accept"
    @change="onChange"
    @update:file-list="onUpdateFileList"
  >
    <template #upload-button>
      <div class="flex items-center justify-center" ref="buttonRef">
        <slot>
          <div class="arco-upload-picture-card">
            <div class="arco-upload-picture-card-text">
              <IconPlus />
            </div>
          </div>
        </slot>
      </div>
    </template>
  </Upload>
</template>
